package titt.server.func;

import titt.TITT;
import titt.TITTValues;
import titt.head.Content;
import titt.head.ContentHead;
import titt.head.FileHead;
import titt.head.HeadFactory;
import titt.head.request.MethodHead;
import titt.head.request.form.FormHead;
import titt.head.response.ResponseHead;
import titt.io.IOFactory;
import titt.io.socket.TITTSocket;
import titt.key.TITTKey;
import titt.server.os.ObjectServer;
import titt.server.service.Service;
import titt.service.ServicePackage;
import titt.service.content.NuderUtil;
import titt.type.TypedObject;
import titt.util.io.pipe.PipeListener;

public class ServiceSyncHelper implements TITTFunction {

	@Override
	public String getMethodName() {
		return "syncHelper";
	}

	private ContentHead warmUp(FormHead fh, TITTSocket ts, int status) {
		try {

			int length = fh.getContentLength();

			byte[] trash = new byte[fh.getBounds()[0].length + TITTValues.HTTP_NEWLINE_LENGTH];

			length -= trash.length;

			ts.getInputStream().read(trash);

			trash = new byte[fh.getBounds()[1].length + 2 * TITTValues.HTTP_NEWLINE_LENGTH];

			FileHead meta = new FileHead(ts.getHeadReader().readHead(false));

			length -= NuderUtil.getHeadLength(meta);
			length -= trash.length;

			return new Content(length, meta.getFileType(), new ResponseHead(status, HeadFactory.EMPTY));	
		}
		catch(Exception e) {
			return null;
		}
	}
	
	@Override
	public void handle(TITTKey key, MethodHead head, final TITTSocket ts, ObjectServer os) throws Exception {
		final TypedObject[] params = head.getParams();

		String packageID = params[1].getObject();

		String[] listenerKey = null;
		
		int status = 200;			
		
		if(params.length > 2)
			status = params[2].getObject();
		
		if(params.length > 3)
			listenerKey = params[3].getObject();
		
		PipeListener l = listenerKey == null? null : IOFactory.createInternalListener(TITT.createProxy(PipeListener.class, listenerKey));
		
		FormHead fh = new FormHead(head);
		
		ContentHead fake = warmUp(fh, ts, status);

		if(fake == null) {
			end(ts, l);
			return;
		}

		ServicePackage pack = new ServicePackage(packageID, fake, ts, l);

		Service ser = os.getServerDatabase().get(pack.getServiceID());

		if(ser == null) {
			end(ts, l);
			return;
		}
		
		ser.sync(pack);
	}
	
	private void end(TITTSocket ts, PipeListener listener) throws Exception {
		if(listener != null)
			listener.onError();
		ts.getHeadWriter().writeHead(new ResponseHead(418, HeadFactory.EMPTY));
		ts.close();
	}

}
